package com.w.picture.config;

import cn.hutool.http.ContentType;
import cn.hutool.http.Header;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import java.io.*;
import java.util.Enumeration;

/**
 * Body重复读取包装.
 *
 * @author wzp
 * @since 2024/9/1
 */
public class RepeatableHttpServletRequestWrapper extends HttpServletRequestWrapper {

    private final byte[] content;
    private final String body;

    public RepeatableHttpServletRequestWrapper(HttpServletRequest request) throws IOException {
        super(request);
        this.body = getStreamAsString(request.getInputStream(), request.getCharacterEncoding());
        this.content = this.body.getBytes(request.getCharacterEncoding());
    }

    public String getBody() {
        return this.body;
    }

    protected static String getStreamAsString(InputStream stream, String charset) throws IOException {
        try {
            Reader reader = new InputStreamReader(stream, charset);
            StringBuilder bodyStringBuilder = new StringBuilder();
            char[] buff = new char[1024];
            int read;
            while ((read = reader.read(buff)) > 0) {
                bodyStringBuilder.append(buff, 0, read);
            }
            return bodyStringBuilder.toString();
        } finally {
            if (stream != null) {
                stream.close();
            }
        }
    }

    @Override
    public BufferedReader getReader() {
        return new BufferedReader(new InputStreamReader(getInputStream()));
    }

    @Override
    public ServletInputStream getInputStream() {
        ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(this.content);
        byteArrayInputStream.reset();
        return new ServletInputStream() {

            @Override
            public int read() {
                return byteArrayInputStream.read();
            }

            @Override
            public boolean isFinished() {
                return false;
            }

            @Override
            public boolean isReady() {
                return true;
            }

            @Override
            public void setReadListener(ReadListener readListener) {

            }
        };
    }

    @Override
    public String getHeader(String name) {
        return super.getHeader(name);
    }

    @Override
    public Enumeration<String> getHeaderNames() {
        return super.getHeaderNames();
    }

    @Override
    public Enumeration<String> getHeaders(String name) {
        return super.getHeaders(name);
    }
}